<?php
 namespace app\models;
 
 use app\models\BaseModel;
 use app\enum\EnumOther;
 use Yii;
 use app\dao\SaleOutDAO;
 use app\dao\SaleOutDetailDAO;
 use app\dao\TransactionDAO;
 use app\dao\ProductDAO;
 use app\dao\ProductUpdateLogDAO;
 use app\helpers\Utility;
 use app\enum\EnumOriginType;
 use app\dao\StockPileDAO;
 use app\dao\QuotesDAO;
 use app\dao\QuotesDetailDAO;
 use app\dao\SellDetailDAO;
 use app\dao\SellDAO;
 use app\dao\SaleReturnDAO;
use app\dao\SaleReturnDetailDAO;
use app\dao\ClientDAO;
use app\dao\WarehouseDAO;
use app\dao\PriceTransactionDAO;
						 
 class SaleModel extends BaseModel
 {
 	/**
 	 * @desc 覆盖父方法返回对象
 	 * @author liaojianwen
 	 * @date 2017-02-07
 	 * @return SaleModel
 	 */
 	public static function model($className=__CLASS__)
 	{
 		return parent::model($className);
 	}
 	
 	/**
 	 * @desc 保存销售发货
 	 * @param [] $head 单头
 	 * @param [] $detail 明细
 	 * @param [] $remove 删除信息
 	 * @param int $id 销售发货单id
 	 * @author liaojianwen
 	 * @date 2017-02-07
 	 */
 	public function saveSaleOut ( $head, $detail, $remove, $id )
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		//清掉为空的元素
 		foreach ($head as $k =>$hed){
			if(empty($hed)){
				unset($head[$k]);
			}
 		}
 		foreach ($detail as $k=> $det){
 			foreach ($det as $j => $deet){
 				if(empty($deet)){
 					unset($detail[$k][$j]);
 				}
 			}
 		}
 		// 表头信息
 		$tr = Yii::$app->db->beginTransaction();
 		try{
 			$head ['saleout_date'] = strtotime ( $head ['saleout_date'] );
 			$cond_head = "saleout_id =:id";
 			$param_head = [
 					':id' => $id
 			];
//  			$Iid = 1;
 			$Iid = SaleOutDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
 			if (! $Iid) {
 				$tr->rollBack();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save saleout_head failure' );
 			}
 			// 表单明细
//  			SaleOutDetailDAO::getInstance()->iupdate(['delete_flag' => EnumOther::DELETED], "saleout_id =:did", [':did'=>$Iid]);// 先删除后没有删除的数据更新回来
			//删除的明细
			foreach ($remove as $move){
				$res_remove = SaleOutDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "saleout_det_id = :det_id", [':det_id'=>$move['saleout_det_id']]);
				if(!$res_remove){
					$tr->rollBack();
					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove saleout_dat_id:'+$move['saleout_det_id'] +'failed');
				}
			}
 			foreach ( $detail as &$det ) {
 				$det ['saleout_id'] = $Iid;
 				$det ['delete_flag'] = EnumOther::NO_DELETE;
 				$cond_det = "saleout_id = :id and saleout_det_id = :lid";
 				$param_det = [
 						':id' => $Iid,
 						':lid' => isset($det ['saleout_det_id'])?$det['saleout_det_id']:0,
 				];
 				$det['minus_quantity'] = $det['base_quantity'];//未退数量
 				
 				//添加 成本 --start
 				$PRODUCT = ProductDAO::getInstance()->iselect("price", "product_id =:pid", [':pid' => $det['product_id']],'one');
 				if(empty($PRODUCT)){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product is null');
 				}
 				$det['cost_price'] = $PRODUCT['price'];
 				$det['cost_amount'] = round(($PRODUCT['price'] * $det['quantity']),2);
 				//---end
 				
 				$res_det = SaleOutDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
 				if (! $res_det) {
 					$tr->rollBack();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save saleout_detail failure' );
 				}
 			}
 			$tr->commit();
 			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 		}catch (\Exception $e){
 			$tr->rollBack();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	
 	/**
 	 * @desc 销售出库单列表
 	 * @param $pageInfo 页面信息
 	 * @param $condition 查询条件
 	 * @param $filter 过滤条件
 	 * @author liaojianwen
 	 * @date 2017-02-07
 	 */
 	public function getSaleOut ( $pageInfo, $condition, $filter)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SaleOutDAO::getInstance()->getSaleOut($condition, $filter, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 编辑页面初始化信息
 	 * @param $id int 销售出库单id
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function getSaleOutInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$in_head = SaleOutDAO::getInstance()->getSaleOutHead($id);
 		if(empty($in_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$in_det = SaleOutDetailDAO::getInstance()->getSaleOutDet($id);
 		if(empty($in_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $in_head;
 		$result['det'] = $in_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 销售出库单明细(弹出框)
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function getSaleOutDet($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'saleout_det_id',
 				'd.saleout_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 		];
 		
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id"
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit"
 				]
 		];
 		$conditions = "d.saleout_id = :id and d.delete_flag = :dflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 		];
 		$result = SaleOutDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"saleout_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 删除销售出库单(相当于入库)
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function delSaleOut($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 		
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_saleout = SaleOutDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_saleout){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_saleout fail');
 				}
 				//saleout_detail
 				$saleout_det = SaleOutDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "saleout_id=:id", [':id'=>$id]);
 				if(!$saleout_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_saleout_det fail');
 				}
 				//更新product_quantity
 				$fields = [
 						't.goods_id',
 						't.quantity',
 						't.transaction_id',
 						'd.quantity_unit',
 						'i.warehouse_id',
 						'i.saleout_no',
 						't.origin_type',
 						'd.quantity_unit',
 						'd.saleout_det_id',
 						'i.sell_id',
 						'd.sell_det_id',
 				];
 				$conditions = "t.delete_flag = :flag";
 				$params = [
 						':flag'=>EnumOther::NO_DELETE,
 				];
 				$joinArray = [
 						[
 								'saleout i',
 								'i.saleout_no = t.origin_id and i.saleout_id = '.$id,
 								'right'=>'',
 						],
 						[
 								'saleout_detail d',
 								'd.saleout_det_id = t.origin_line_id',
 								'left'=>''
 						]
 				];
 				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
 				if (! empty ( $trans_select )) {
 					// 已确认的入库单才有transtions,减库存
 					foreach ( $trans_select as $trans ) {
 						//记录更新product 前的quantity
 						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
 						//product 更新数量
 						$pro_minus = ProductDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => $trans ['quantity'],
 						], "product_id =:id", [
 								':id' => $trans ['goods_id']
 						] );
 							
 						if (! $pro_minus) {
 							$tT->rollBack();
 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 						}
 		
 						//product_update_log 商品更新记录
 						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['origin_type']);
 		
 						$log_columns = [
 								'product_id' => $trans ['goods_id'],
 								'update_num' => $trans ['quantity'],
 								'num_unit' => $trans['quantity_unit'],
 								'origin_id' => $id,
 								'origin_no' => $trans['saleout_no'],
 								'origin_line_id'=> $trans['saleout_det_id'],
 								'origin_type'=> $trans['origin_type'],
 								'update_time'=> strtotime(date('Y-m-d')),
 								'flag'=> EnumOther::IN_FLAG,
 								'initial_num'=> $PRODUCT['quantity'],//上期数量
 								'remark'=> $_order_type . EnumOther::PLUS.',销售出库单删除',
 								'warehouse_id' => $trans['warehouse_id'],
 								'create_man' => Yii::$app->user->id,
 						];
 						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 						if(! $res_log){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 						}
 		
 						//删除transaction 数据
 						$columns = [
 								'delete_flag'=>EnumOther::DELETED,
 						];
 						$conditions = "transaction_id = :tid";
 						$params = [
 								':tid'=>$trans['transaction_id'],
 						];
 						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
 		
 						if(empty($trans_update)){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
 						}
 						// 更新stock_file 分仓表信息
 						$stock_minus = StockPileDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => $trans ['quantity']
 						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
 								':wid' => $trans ['warehouse_id'],
 								':pid' => $trans ['goods_id'],
 								':flag' => EnumOther::NO_DELETE
 						] );
 						if(! $stock_minus){
 							$tT->rollBack ();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
 						}
 						//更新sell
 						if($trans['sell_id']){
	 						$result = SellDAO::getInstance()->updateSell($trans['sell_id'],$trans['sell_det_id'],$trans['quantity']);
	 						if(!$result){
	 							$tT->rollBack();
	 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update sell failure');
	 						}
 						}
 					}
 				}
 			}
 		
 			$tT->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 确认销售出库单
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function confirmSaleOut($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$id = (int)$id;
 		$tr = Yii::$app->db->beginTransaction ();
 		try {
 			$re_confirm = SaleOutDAO::getInstance ()->updateByPk ( $id, [
 					'confirm_flag' => EnumOther::CONFIRM
 			] );
 			if (! $re_confirm) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
 			}
 			$fields = [
 					'h.saleout_id',
 					'h.saleout_no',
 					'd.product_id',
 					'd.quantity',
 					'h.saleout_type',
 					'd.saleout_det_id',
 					'h.warehouse_id',
 					'h.saleout_date',
 					'd.quantity_unit',
 					'd.base_quantity',
 					'd.base_unit',
 					'h.customer_id',
 					'h.sell_id',
 					'd.sell_det_id',
 					's.quantity squantity',
 					'd.cost_price',
 					'd.cost_amount',
 					'd.base_price',
 					'd.amount',
 			];
 			$conditions = "d.saleout_id =:id and d.delete_flag = :flag";
 			$params = [
 					':id' => $id,
 					':flag' => EnumOther::NO_DELETE
 			];
 			$joinArray = [
 					[
 							'saleout h',
 							"h.saleout_id = d.saleout_id"
 					],
 					[
 							'stock_pile s',
 							"s.product_id = d.product_id and s.warehouse_id = h.warehouse_id"
 					]
 			];
 			$saleout_det = SaleOutDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.saleout_det_id ASC', $joinArray, 'd' );
 			if (! $saleout_det) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
 			}
 			// 出库明细
 			foreach ( $saleout_det as $det ) {
 				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity","product_name"], "product_id = :pid", [':pid'=>$det['product_id']],'one');
 				if(isset($PRODUCT['price'])){
 					$price = $PRODUCT['price'];
 				} else {
 					$price = 0;
 				}

 				if($det['base_quantity'] > $det['squantity']){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,$PRODUCT['product_name'],'overflow quantity');
 				}
 				
 				$column_trans = array (
 						'goods_id' => $det ['product_id'],
 						'quantity' => $det ['base_quantity'],
 						'quantity_unit'=> $det['base_unit'],
 						'origin_type' => $det['saleout_type'],
 						'origin_id' => $det ['saleout_no'],
 						'origin_line_id' => $det ['saleout_det_id'], // 原单序号
 						'origin_time'=>$det['saleout_date'],
 						'warehouse_id' => $det ['warehouse_id'],
 						'flag' => EnumOther::OUT_FLAG,
 						'init_num' => $PRODUCT['quantity'],//上期数量
 						'customer_id' => $det['customer_id'],
 				);
 		
 				$res_trans = TransactionDAO::getInstance ()->iinsert ( $column_trans, true );
 				if (! $res_trans) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failure' );
 				}
 		
 		

 				// 更新product quantity 减库存
 				$WAREHOUSE = WarehouseDAO::getInstance()->iselect("is_scrapped,warehouse_name", "warehouse_id =:wid", [':wid'=>$det['warehouse_id']],'one');
 				if(isset($WAREHOUSE['is_scrapped'])){
 					if($WAREHOUSE['is_scrapped'] != '1'){//不是报废单
		 				$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
		 						'quantity' => - $det ['base_quantity'],
								'amount' => - ($det ['base_quantity'] * $price) 
						], "product_id =:id", [ 
								':id' => $det ['product_id'] 
						] );
						if (! $pro_select) {
							$tr->rollBack ();
							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
						}
					}
				} else {
					$tr->rollBack ();
					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select scrapped failed' );
				}
					
				// price_transaction
				$price_trans = [ 
						'product_id' => $det ['product_id'],
						'quantity' => $det ['base_quantity'],
						'quantity_unit' => $det ['base_unit'],
						'price' => $det ['base_price'],
						'amount' => $det ['amount'],
						'origin_type' => $det['saleout_type'],
						'origin_id' => $det ['saleout_id'],
						'origin_no' => $det ['saleout_no'],
						'origin_line_id' => $det ['saleout_det_id'], // 原单序号
						'origin_time' => $det ['saleout_date'],
						'warehouse_id' => $det ['warehouse_id'], // 调出仓库
						'cost_price' => $det ['cost_price'],
						'cost_amount' => $det ['cost_amount'],
						'customer_id' => $det['customer_id'],//客户
		 			];
		 		$price_res = PriceTransactionDAO::getInstance()->iinsert($price_trans, true);
		 		if(! $price_res){
		 			$tr->rollBack();
		 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'save price transaction failed');
		 		}
		 		//---end
		 		
 				//product_update_log 商品更新记录
 				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type,$det['saleout_type']);
 		
 				$log_columns = [
 						'product_id' => $det ['product_id'],
 						'update_num' => $det ['base_quantity'],
 						'num_unit' => $det['base_unit'],
 						'origin_id' => $id,
 						'origin_no' => $det ['saleout_no'],
 						'origin_line_id'=> $det['saleout_det_id'],
 						'origin_type'=>$det['saleout_type'],
 						'update_time'=>strtotime(date('Y-m-d')),
 						'flag'=> EnumOther::OUT_FLAG,
 						'initial_num'=> $PRODUCT['quantity'],//上期数量
 						'remark'=> $_order_type .($WAREHOUSE['warehouse_name']?:''). EnumOther::MINUS,
 						'warehouse_id' => $det['warehouse_id'],
 						'create_man' => Yii::$app->user->id,
 				];
 				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 				if(! $res_log){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 				}
 		
 				//采购订单表回写//是由导入采购订单的入库单才要执行下面代码
 				$sell_id = $det['sell_id'];
 				if($sell_id){
 					$sell_finish = SellDetailDAO::getInstance()->updateFinish($sell_id,$det);
 					if($sell_finish['Ack'] == 'error'){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$sell_finish['msg']);
 					}
 				}
 				
 		
 				//分仓列表数据的插入或者更新--start
 				$stock_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stock_params = [
 						':wid'=>$det['warehouse_id'],
 						':pid'=>$det['product_id'],
 						':flag'=> EnumOther::NO_DELETE,
 				];
 				$stock_select = StockPileDAO::getInstance()->iselect("stock_pile_id", $stock_conditions, $stock_params,'one');
 				if(! $stock_select){
 					//没有数据，插入新数据
 					// 					$stock_columns = [
 					// 							'warehouse_id'=> $det['warehouse_id'],
 					// 							'product_id'=> $det['goods_id'],
 					// 							'quantity'=> $det['quantity'],
 					// 							'quantity_unit'=> $det['unit'],
 					// 					];
 					// 					$stock_insert = StockPileDAO::getInstance()->iinsert($stock_columns, true);
 					// 					if(! $stock_insert){
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select stock pile failure' );
 					// 					}
 				} else {
 					//有数据，更新数据
 					$stock_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> -$det['base_quantity']], $stock_conditions, $stock_params);
 					if(! $stock_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//分仓 --end
 		
 			}
 			$tr->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tr->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 获取赠送明细
 	 * @author liaojianwen
 	 * @date 2017-03-29
 	 */
 	public function getSaleoutFree($condition, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','param is empty');
 		}
 		$result = SaleOutDAO::getInstance()->getSaleoutFree($condition,$pageInfo);
 		if(!$result){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 获取赠送明细导出数据
 	 * @author liaojianwen
 	 * @date 2017-03-30
 	 */
 	public function getSaleFreeExport($condition)
 	{
 		if(empty($condition)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'condition is null');
 		}
 		$result = SaleOutDAO::getInstance()->getSaleoutExport($condition);
 		if(!$result){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 导出赠送明细
 	 * @author liaojianwen
 	 * @date 2017-03-30
 	 */
 	public function exportSaleoutFree($dataInfo, $filename, $title, $excVer = "xls")
 	{
 		$data = $dataInfo['list'];
 		$objPHPExecl = new \PHPExcel();
 		$objSheet = $objPHPExecl->getActiveSheet()->setTitle('出库明细');
 		$objWriter = NULL;
 		// 创建文件格式写入对象实例
 		switch ($excVer){
 			case 'xlsx':
 				$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExecl);
 				break;
 			case 'xls':
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 				break;
 			default:
 				$objWriter = new \PHPExcel_Writer_Excel5($objPHPExecl);
 		}
 		//设置宽度
 		$objSheet->mergeCells("A1:H2");
 		$objSheet->setCellValue("A1", $title);
 		$objSheet->getStyle('A1')->getFont()->setSize(26);
 		$objSheet->getStyle('A1')->getFont()->setBold(true);
 		$objSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
 		
 		$objSheet->getColumnDimension('A')->setWidth(20);
 		$objSheet->getColumnDimension('B')->setWidth(20);
 		$objSheet->getColumnDimension('C')->setWidth(20);
 		$objSheet->getColumnDimension('D')->setWidth(20);
 		$objSheet->getColumnDimension('E')->setWidth(20);
 		$objSheet->getColumnDimension('F')->setWidth(20);
 		$objSheet->getColumnDimension('G')->setWidth(20);
 		$objSheet->getColumnDimension('H')->setWidth(20);
 		$objSheet->setCellValue('A3', '销售（出库）日期');
 		$objSheet->getStyle('A3')->getFont()->setBold(true);
 		$objSheet->setCellValue('B3', '客户');
 		$objSheet->getStyle('B3')->getFont()->setBold(true);
 		$objSheet->setCellValue('C3', '商品');
 		$objSheet->getStyle('C3')->getFont()->setBold(true);
 		$objSheet->setCellValue('D3', '单位');
 		$objSheet->getStyle('D3')->getFont()->setBold(true);
 		$objSheet->setCellValue('E3', '数量');
 		$objSheet->getStyle('E3')->getFont()->setBold(true);
 		$objSheet->setCellValue('F3', '进价');
 		$objSheet->getStyle('F3')->getFont()->setBold(true);
 		$objSheet->setCellValue('G3', '总价');
 		$objSheet->getStyle('G3')->getFont()->setBold(true);
 		$objSheet->setCellValue('H3', '备注');
 		$objSheet->getStyle('H3')->getFont()->setBold(true);
 		$i = 'A';
		for($n = 0; $n < 8; $n ++) {
			$count = $i ++;
			$objSheet->getStyle ( $count . '3' )->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		}
 	
 		$rowNum = 4;
 		foreach($data as $det){
 			$saleout_date = $det['saleout_date'] ? date('Y-m-d', $det['saleout_date']) : '';
 			$amount = $det['price'] * $det['base_quantity'];
 			
 			$this->_genExcelFont($objSheet, "A".$rowNum, "A".$rowNum, $saleout_date, false);
 			$this->_genExcelFont($objSheet, "B".$rowNum, "B".$rowNum, $det['client_name'], false);
 			$this->_genExcelFont($objSheet, "C".$rowNum, "C".$rowNum, $det['product_name'], false);
 			$this->_genExcelFont($objSheet, "D".$rowNum, "D".$rowNum, $det['unit_name'], false);
 			$this->_genExcelFont($objSheet, "E".$rowNum, "E".$rowNum, $det['base_quantity'], false);
 			$this->_genExcelFont($objSheet, "F".$rowNum, "F".$rowNum, $det['price'], false);
 			$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $amount, false);
 			$this->_genExcelFont($objSheet, "H".$rowNum, "H".$rowNum, $det['remark'], false);
 	
 			$rowNum++;
 		}
 		$this->_genExcelFont($objSheet, "G".$rowNum, "G".$rowNum, $dataInfo['total_amount'], false);
 		
 		ob_end_clean(); // 去掉缓存
 		header("Content-Type: application/force-download");
 		header("Content-Type: application/octet-stream");
 		header("Content-Type: application/download");
 		header('Content-Disposition:inline;filename="' . $filename . '.xls"');
 		header("Content-Transfer-Encoding: binary");
 		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
 		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
 		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
 		header("Pragma: no-cache");
 		//  		            $objWriter->save("upload/demo.xlsx");
 		$objWriter->save('php://output');
 	}
 	
 	
 	/**
 	 * @desc 获取销售发货
 	 * @author liaojianwen
 	 * @date 2017-03-30
 	 * ///////暂时不用，销售单统计，在商场完成
 	 */
 	public function getSaleoutCount($condition, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','param is empty');
 		}
 		$result = SaleOutDAO::getInstance()->getSaleoutCount($condition,$pageInfo);
 		if(!$result){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	
 	
 	
 	/**
 	 * @desc 保存报价单
 	 * @author liaojianwen
 	 * @date 2017-03-24
 	 */
 	public function saveQuotes ( $head, $detail, $remove, $id )
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		$tr = Yii::$app->db->beginTransaction();
 		try{
	 		if(empty($id)){
	 			$id = 0;
	 		}
	 	
	 		//清掉为空的元素
	 		foreach ($head as $k =>$hed){
	 			if(empty($hed)){
	 				unset($head[$k]);
	 			}
	 		}
	 		foreach ($detail as $k=> $det){
	 			foreach ($det as $j => $deet){
	 				if(empty($deet)){
	 					unset($detail[$k][$j]);
	 				}
	 			}
	 		}
	 		// 表头信息
	 		$head ['quotes_time'] = strtotime ( $head ['quotes_time'] );
	//  		$head ['receive_date'] = strtotime ( $head ['receive_date'] );
	 		$cond_head = "quotes_id =:id";
	 		$param_head = [
	 				':id' => $id
	 		];
	 		$Iid = QuotesDAO::getInstance()->ireplaceinto ( $head, $cond_head, $param_head, true );
	 		if (! $Iid) {
	 			$tr->rollBack();
	 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save quotes_head failure' );
	 		}
	 		//删除的明细
	 		foreach ($remove as $move){
	 			$res_remove = QuotesDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "quotes_det_id = :det_id", [':det_id'=>$move['quotes_det_id']]);
	 			if(!$res_remove){
	 				$tr->rollBack();
	 				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove quotes_det_id:'+$move['quotes_det_id'] +'failed');
	 			}
	 		}
	 		foreach ( $detail as &$det ) {
	 			$det ['quotes_id'] = $Iid;
	 			$det ['delete_flag'] = EnumOther::NO_DELETE;
	 			$cond_det = "quotes_id = :id and quotes_det_id = :lid";
	 			$param_det = [
	 					':id' => $Iid,
	 					':lid' => isset($det ['quotes_det_id'])?$det['quotes_det_id']:0
	 			];
	 			$res_det = QuotesDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
	 			if (! $res_det) {
	 				$tr->rollBack();
	 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save quotes_detail failure' );
	 			}
	 		}
	 		
	 		$tr->commit();
	 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 		} catch (\Exception $e){
 			$tr->rollBack();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 获取销售报价单列表数据
 	 * @param [] $pageInfo 页面/页码数据
 	 * @param [] $condition 查询数据
 	 * @author liaojianwen
 	 * @date 2017-03-27
 	 */
 	public function getQuotes($pageInfo, $condition)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
 		}
 		$result = QuotesDAO::getInstance()->getQuotes($condition, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 获取编辑状态下报价单的信息
 	 * @param int $id  报价单单号
 	 * @author liaojianwen
 	 * @date 2017-03-27
 	 */
 	public function getQuotesInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pro_head = QuotesDAO::getInstance()->getQuotesHead($id);
 		if(empty($pro_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pro_det = QuotesDetailDAO::getInstance()->getQuotesDet($id);
 		if(empty($pro_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $pro_head;
 		$result['det'] = $pro_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @descs 删除采购报价单
 	 * @author liaojianwen
 	 * @date 2017-03-28
 	 */
 	public function delQuotes($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 	
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_finish = QuotesDAO::getInstance()->findByAttributes('finish_flag',"quotes_id=:id",[':id'=>$id]);
 				if(isset($res_finish['finish_flag']) && $res_finish['finish_flag']){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','finish order can not be delete');
 				}
 				$res_quotes = QuotesDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_quotes){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_quotes fail');
 				}
 				//
 				$quotes_det = QuotesDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "quotes_id=:id", [':id'=>$id]);
 				if(!$quotes_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_quotes_det fail');
 				}
 				$tT->commit();
 				return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 			}
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return false;
 		}
 	}
 	
 	/**
 	 * @desc 保存报价单
 	 * @author liaojianwen
 	 * @date 2017-03-24
 	 */
 	public function saveSell ( $head, $detail, $remove, $id )
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		
 		$tr = Yii::$app->db->beginTransaction();
 		try{
	 		if(empty($id)){
	 			$id = 0;
	 		} else {
		 		$res_sale = SaleOutDAO::getInstance()->findByAttributes('sell_id',"sell_id =:pid and delete_flag=:fflag",[':pid' =>$id, ':fflag'=>EnumOther::NO_DELETE]);
		 		if($res_sale !=false){
		 			$tr->rollBack();
		 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'exits next order');
		 		}
	 		}
	 		//清掉为空的元素
	 		foreach ($head as $k =>$hed){
	 			if(empty($hed)){
	 				unset($head[$k]);
	 			}
	 		}
	 		foreach ($detail as $k=> $det){
	 			foreach ($det as $j => $deet){
	 				if(empty($deet)){
	 					unset($detail[$k][$j]);
	 				}
	 			}
	 		}
	 		// 表头信息
	 		$head ['sell_date'] = strtotime ( $head ['sell_date'] );
	 		$cond_head = "sell_id =:id";
	 		$param_head = [
	 				':id' => $id
	 		];
	 		$Iid = SellDAO::getInstance()->ireplaceinto ( $head, $cond_head, $param_head, true );
	 		if (! $Iid) {
	 			$tr->rollBack();
	 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save sell_head failure' );
	 		}
	 		//删除的明细
	 		foreach ($remove as $move){
	 			$res_remove = SellDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "sell_det_id = :det_id", [':det_id'=>$move['sell_det_id']]);
	 			if(!$res_remove){
	 				$tr->rollBack();
	 				$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove sell_det_id:'+$move['sell_det_id'] +'failed');
	 			}
	 		}
	 		foreach ( $detail as &$det ) {
	 			$det ['sell_id'] = $Iid;
	 			$det ['delete_flag'] = EnumOther::NO_DELETE;
	 			$cond_det = "sell_id = :id and sell_det_id = :lid";
	 			$param_det = [
	 					':id' => $Iid,
	 					':lid' => isset($det ['sell_det_id'])?$det['sell_det_id']:0
	 			];
	 			$det['minus_quantity'] = $det['base_quantity'];
// 	 			$PRODUCT = ProductDAO::getInstance()->iselect("price", "product_id =:pid", [':pid' => $det['product_id']],'one');
// 	 			if(empty($PRODUCT)){
// 	 				$tr->rollBack();
// 	 				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product is null');
// 	 			}
// 	 			$det['cost_price'] = $PRODUCT['price'];
// 	 			$det['cost_amount'] = round(($PRODUCT['price'] * $det['quantity']),2);
	 			$res_det = SellDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
	 			if (! $res_det) {
	 				$tr->rollBack();
	 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save sell_detail failure' );
	 			}
	 		}
	 		$tr->commit();
	 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 		} catch (\Exception $e){
 			$tr->rollBack();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 获取销售订单列表数据
 	 * @param [] $pageInfo 页面/页码数据
 	 * @param [] $condition 查询数据
 	 * @param int $filter 过滤条件
 	 * @author liaojianwen
 	 * @date 2017-04-13
 	 */
 	public function getSells($pageInfo, $condition, $filter)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
 		}
 		$result = SellDAO::getInstance()->getSells($condition, $pageInfo, $filter);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	
 	/**
 	 * @desc 获取编辑状态下销售定单的信息
 	 * @param int $id  销售订单单号
 	 * @author liaojianwen
 	 * @date 2017-04-14
 	 */
 	public function getSellInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pro_head = SellDAO::getInstance()->getSellHead($id);
 		if(empty($pro_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pro_det = SellDetailDAO::getInstance()->getSellDet($id);
 		if(empty($pro_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $pro_head;
 		$result['det'] = $pro_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 查询销售订单（导入订单）
 	 * @param $cond 查询条件
 	 * @param $pageInfo 页面信息
 	 * @author liaojianwen
 	 * @date 2017-04-14
 	 */
 	public function selectSell($cond, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SellDAO::getInstance()->selectSell($cond, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	/**
 	 * @desc 销售定单明细(弹出框)
 	 * @author liaojianwen
 	 * @date 2017-04-14
 	 */
 	public function getSellDet($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'sell_det_id',
 				'd.sell_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 		];
 			
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id"
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit"
 				]
 		];
 		$conditions = "d.sell_id = :id and d.delete_flag = :dflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 		];
 		$result = SellDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"sell_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 删除销售订单
 	 * @author liaojianwen
 	 * @date 2017-04-14
 	 */
 	public function delSell($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 	
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_finish = SellDAO::getInstance()->findByAttributes('finish_flag',"sell_id=:id",[':id'=>$id]);
 				if(isset($res_finish['finish_flag']) && $res_finish['finish_flag']){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','finish order can not be delete');
 				}
 				$res_sell = SellDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_sell){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_sell fail');
 				}
 				//sell_detail
 				$sell_det = SellDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "sell_id=:id", [':id'=>$id]);
 				if(!$sell_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_sell_det fail');
 				}
 				$tT->commit();
 				return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 			}
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return false;
 		}
 	}
 	
 	/**
 	 * @desc 根据订单id 获取明细信息（导入销售订单）
 	 * @author liaojianwen
 	 * @date 2017-04-13
 	 */
 	public function getSellDetail($id)
 	{
 		if (empty ( $id )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'sell_det_id',
 				'd.sell_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 				'd.minus_quantity',
 				'd.shipped_quantity',
 		];
 	
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id",
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit",
 				]
 		];
 		$conditions = "d.sell_id = :id and d.delete_flag = :dflag and d.finish_flag =:fflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 				':fflag' => EnumOther::NO_FINISHED,
 		];
 		$result = SellDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"sell_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	/**
 	 * @desc 检查订单是否被出库单占用
 	 * @author liaojianwen
 	 * @date 2017-04-14
 	 */
 	public function checkSellById($id)
 	{
 		if(!$id){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SaleOutDAO::getInstance ()->findByAttributes ( "saleout_id", "sell_id =:pid and confirm_flag=:flag and delete_flag =:dflag", [
 				':pid' => $id,
 				':flag' => EnumOther::NO_CONFIRM ,
 				':dflag' => EnumOther::NO_DELETE,
 		] );
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 	}
 	
 	
 	/**
 	 * @desc 查询销售出库（导入出库单）
 	 * @param $cond 查询条件
 	 * @param $pageInfo 页面信息
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function selectSaleOut($cond, $pageInfo)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SaleOutDAO::getInstance()->selectSaleOut($cond, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	/**
 	 * @desc 根据销售出库id 获取明细信息（导入销售出库）
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function getSaleOutDetail($id)
 	{
 		if (empty ( $id )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'saleout_det_id',
 				'd.saleout_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 				'd.minus_quantity',
 				'd.return_quantity',
 		];
 	
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id",
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit",
 				]
 		];
 		$conditions = "d.saleout_id = :id and d.delete_flag = :dflag and d.finish_flag =:fflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 				':fflag' => EnumOther::NO_FINISHED,
 		];
 		$result = SaleOutDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"saleout_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail no data found');
 		}
 		return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, $result );
 	}
 	
 	/**
 	 * @desc 检查出库单是否被退货单占用
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function checkSaleOutById($id)
 	{
 		if(!$id){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SaleReturnDAO::getInstance ()->findByAttributes ( "salereturn_id", "saleout_id =:pid and confirm_flag=:flag and delete_flag =:dflag", [
 				':pid' => $id,
 				':flag' => EnumOther::NO_CONFIRM ,
 				':dflag' => EnumOther::NO_DELETE,
 		] );
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 	}
 	
 	/**
 	 * @desc 保存销售退货
 	 * @param [] $head 单头
 	 * @param [] $detail 明细
 	 * @param [] $remove 删除信息
 	 * @param int $id 销售退货单id
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function saveSaleReturn ( $head, $detail, $remove, $id )
 	{
 		if(empty($head)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'head is empty' );
 		}
 		if (empty ( $detail )) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'detail is empty' );
 		}
 		//清掉为空的元素
 		foreach ($head as $k =>$hed){
 			if(empty($hed)){
 				unset($head[$k]);
 			}
 		}
 		foreach ($detail as $k=> &$det){
 			if($det['second_quantity'] == ''){
 				$det['second_quantity'] = '0';
 			}
 			foreach ($det as $j => $deet){
 				if($deet == ''){
 					unset($detail[$k][$j]);
 				}
 			}
 		}
 		// 表头信息
 		$tr = Yii::$app->db->beginTransaction();
 		try{
 			$head ['salereturn_date'] = strtotime ( $head ['salereturn_date'] );
 			$cond_head = "salereturn_id =:id";
 			$param_head = [
 					':id' => $id
 			];
 			//  			$Iid = 1;
 			// 			dd($head);
 			$Iid = SaleReturnDAO::getInstance ()->ireplaceinto ( $head, $cond_head, $param_head, true );
 			if (! $Iid) {
 				$tr->rollBack();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save salereturn_head failure' );
 			}
 			// 表单明细
 			//删除的明细
 			foreach ($remove as $move){
 				$res_remove = SaleReturnDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "salereturn_det_id = :det_id", [':det_id'=>$move['salereturn_det_id']]);
 				if(!$res_remove){
 					$tr->rollBack();
 					$this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'remove salereturn_dat_id:'+$move['salereturn_det_id'] +'failed');
 				}
 			}
 			foreach ( $detail as &$det ) {
 				$det ['salereturn_id'] = $Iid;
 				$det ['delete_flag'] = EnumOther::NO_DELETE;
 				$cond_det = "salereturn_id = :id and salereturn_det_id = :lid";
 				$param_det = [
 						':id' => $Iid,
 						':lid' => isset($det ['salereturn_det_id'])?$det['salereturn_det_id']:0,
 				];
 				$res_det = SaleReturnDetailDAO::getInstance ()->ireplaceinto ( $det, $cond_det, $param_det, true );
 				if (! $res_det) {
 					$tr->rollBack();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save salereturn_detail failure' );
 				}
 			}
 			$tr->commit();
 			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
 		}catch (\Exception $e){
 			$tr->rollBack();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 销售退货单列表
 	 * @param $pageInfo 页面信息
 	 * @param $condition 查询条件
 	 * @param $filter 过滤条件
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function getSaleReturn ( $pageInfo, $condition, $filter)
 	{
 		if(empty($pageInfo)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$result = SaleReturnDAO::getInstance()->getSaleReturn($condition, $filter, $pageInfo);
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 编辑页面初始化信息（销售退货单）
 	 * @param $id int 销售退货单id
 	 * @author liaojianwen
 	 * @date 2017-04-25
 	 */
 	public function getSaleReturnInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$in_head = SaleReturnDAO::getInstance()->getSaleReturnHead($id);
 		if(empty($in_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$in_det = SaleReturnDetailDAO::getInstance()->getSaleReturnDet($id);
 		if(empty($in_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		$result['head'] = $in_head;
 		$result['det'] = $in_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 销售退货单明细(弹出框)
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function getSaleReturnDet($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$fields = [
 				'salereturn_det_id',
 				'd.salereturn_id',
 				'd.product_id',
 				'p.product_name',
 				'p.product_sn',
 				'd.quantity',
 				'd.quantity_unit',
 				'u.unit_name',
 				'd.price',
 				'd.amount',
 				'd.remark',
 		];
 			
 		$joinArr = [
 				[
 						"product p",
 						"p.product_id = d.product_id"
 				],
 				[
 						"unit u",
 						"u.unit_id = d.quantity_unit"
 				]
 		];
 		$conditions = "d.salereturn_id = :id and d.delete_flag = :dflag";
 		$params = [
 				':id' => $id,
 				':dflag' => EnumOther::NO_DELETE,
 		];
 		$result = SaleReturnDetailDAO::getInstance()->iselect($fields, $conditions, $params, 'all',"salereturn_det_id ASC", $joinArr,'d');
 		if(empty($result)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, $result);
 	}
 	
 	/**
 	 * @desc 确认销售退货单
 	 * @author liaojianwen
 	 * @date 2017-02-08
 	 */
 	public function confirmSaleReturn($id)
 	{
 		if (! $id) {
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$id = (int)$id;
 		$tr = Yii::$app->db->beginTransaction ();
 		try {
 			$re_confirm = SaleReturnDAO::getInstance ()->updateByPk ( $id, [
 					'confirm_flag' => EnumOther::CONFIRM
 			] );
 			if (! $re_confirm) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'confirm fail' );
 			}
 			$fields = [
 					'h.salereturn_no',
 					'd.product_id',
 					'd.quantity',
 					'h.salereturn_type',
 					'd.salereturn_det_id',
 					'h.warehouse_id',
 					'h.salereturn_date',
 					'd.quantity_unit',
 					'd.base_quantity',
 					'd.base_unit',
 					'h.customer_id',
 					'h.saleout_id',
 					'd.saleout_det_id',
 			];
 			$conditions = "d.salereturn_id =:id and d.delete_flag = :flag";
 			$params = [
 					':id' => $id,
 					':flag' => EnumOther::NO_DELETE
 			];
 			$joinArray = [
 					[
 							'salereturn h',
 							"h.salereturn_id = d.salereturn_id"
 					]
 			];
 			$salereturn_det = SaleReturnDetailDAO::getInstance ()->iselect ( $fields, $conditions, $params, 'all', 'd.salereturn_det_id ASC', $joinArray, 'd' );
 			if (! $salereturn_det) {
 				$tr->rollBack ();
 				return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'select det fail' );
 			}
 			// 出库明细
 			foreach ( $salereturn_det as $det ) {
 				$PRODUCT = ProductDAO::getInstance()->iselect(["price","quantity"], "product_id = :pid", [':pid'=>$det['product_id']],'one');
 				if(isset($PRODUCT['price'])){
 					$price = $PRODUCT['price'];
 				} else {
 					$price = 0;
 				}
 					
 				$column_trans = array (
 						'goods_id' => $det ['product_id'],
 						'quantity' => $det ['base_quantity'],
 						'quantity_unit'=> $det['base_unit'],
 						'origin_type' => $det['salereturn_type'],
 						'origin_id' => $det ['salereturn_no'],
 						'origin_line_id' => $det ['salereturn_det_id'], // 原单序号
 						'origin_time'=>$det['salereturn_date'],
 						'warehouse_id' => $det ['warehouse_id'],
 						'flag' => EnumOther::IN_FLAG,
 						'init_num' => $PRODUCT['quantity'],//上期数量
 						'customer_id' => $det['customer_id'],
 				);
 					
 				$res_trans = TransactionDAO::getInstance ()->iinsert ( $column_trans, true );
 				if (! $res_trans) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'save transaction failure' );
 				}
 					
 					
 	
 				// 更新product quantity 增库存
 				$pro_select = ProductDAO::getInstance ()->updateAllCounters ( [
 						'quantity' => $det ['base_quantity'],
 						'amount' => ($det['base_quantity'] * $price)
 				], "product_id =:id", [
 						':id' => $det ['product_id']
 				] );
 				if (! $pro_select) {
 					$tr->rollBack ();
 					return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 				}
 					
 				//product_update_log 商品更新记录
 				$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type,$det['salereturn_type']);
 					
 				$log_columns = [
 						'product_id' => $det ['product_id'],
 						'update_num' => $det ['base_quantity'],
 						'num_unit' => $det['base_unit'],
 						'origin_id' => $id,
 						'origin_no' => $det ['salereturn_no'],
 						'origin_line_id'=> $det['salereturn_det_id'],
 						'origin_type'=>$det['salereturn_type'],
 						'update_time'=>strtotime(date('Y-m-d')),
 						'flag'=> EnumOther::IN_FLAG,
 						'initial_num'=> $PRODUCT['quantity'],//上期数量
 						'remark'=> $_order_type . EnumOther::PLUS,
 						'warehouse_id' => $det['warehouse_id'],
 						'create_man' => Yii::$app->user->id,
 				];
 				$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 				if(! $res_log){
 					$tr->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 				}
 					
 				//采购订单表回写//是由导入采购订单的入库单才要执行下面代码
 				$saleout_id = $det['saleout_id'];
 				if($saleout_id){
 					$saleout_finish = SaleOutDetailDAO::getInstance()->updateFinish($saleout_id,$det);
 					if($saleout_finish['Ack'] == 'error'){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$saleout_finish['msg']);
 					}
 				}
 					
 					
 				//分仓列表数据的插入或者更新--start
 				$stock_conditions = "warehouse_id =:wid and product_id=:pid and delete_flag =:flag";
 				$stock_params = [
 						':wid'=>$det['warehouse_id'],
 						':pid'=>$det['product_id'],
 						':flag'=> EnumOther::NO_DELETE,
 				];
 				$stock_select = StockPileDAO::getInstance()->iselect("stock_pile_id", $stock_conditions, $stock_params,'one');
 				if(! $stock_select){
 					//没有数据，插入新数据
 					$stock_columns = [
 							'warehouse_id'=> $det['warehouse_id'],
 							'product_id'=> $det['goods_id'],
 							'quantity'=> $det['base_quantity'],
 							'quantity_unit'=> $det['base_unit'],
 					];
 					$stock_insert = StockPileDAO::getInstance()->iinsert($stock_columns, true);
 					if(! $stock_insert){
 						$tr->rollBack ();
 						return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'insert stock pile failure' );
 					}
 				} else {
 					//有数据，更新数据
 					$stock_update = StockPileDAO::getInstance()->updateAllCounters(['quantity'=> $det['base_quantity']], $stock_conditions, $stock_params);
 					if(! $stock_update){
 						$tr->rollBack();
 						return $this->handleApiFormat(EnumOther::ACK_FAILURE, '','update stock pile failure');
 					}
 				}
 				//分仓 --end
 					
 			}
 			$tr->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tr->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'',$e->getMessage());
 		}
 	}
 	
 	
 	/**
 	 * @desc 删除销售退货单(相当于出库)
 	 * @author liaojianwen
 	 * @date 2017-04-26
 	 */
 	public function delSaleReturn($ids)
 	{
 		if(empty($ids)){
 			return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'param is empty' );
 		}
 		$_ids = explode ( ',', $ids );
 			
 		$tT = Yii::$app->db->beginTransaction ();
 		try {
 			foreach ( $_ids as $id ) {
 				$res_salereturn = SaleReturnDAO::getInstance ()->updateByPk ( $id, ['delete_flag' => EnumOther::DELETED] );
 				if(!$res_salereturn){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'del_salereturn fail');
 				}
 				//salereturn_detail
 				$salereturn_det = SaleReturnDetailDAO::getInstance()->iupdate(['delete_flag'=>EnumOther::DELETED], "salereturn_id=:id", [':id'=>$id]);
 				if(!$salereturn_det){
 					$tT->rollBack();
 					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del_salereturn_det fail');
 				}
 				//更新product_quantity
 				$fields = [
 						't.goods_id',
 						't.quantity',
 						't.transaction_id',
 						'd.quantity_unit',
 						'i.warehouse_id',
 						'i.salereturn_no',
 						't.origin_type',
 						'd.quantity_unit',
 						'd.salereturn_det_id',
 						'i.saleout_id',
 						'd.saleout_det_id',
 				];
 				$conditions = "t.delete_flag = :flag";
 				$params = [
 						':flag'=>EnumOther::NO_DELETE,
 				];
 				$joinArray = [
 						[
 								'salereturn i',
 								'i.salereturn_no = t.origin_id and i.salereturn_id = '.$id,
 								'right'=>'',
 						],
 						[
 								'salereturn_detail d',
 								'd.salereturn_det_id = t.origin_line_id',
 								'left'=>''
 						]
 				];
 				$trans_select = TransactionDAO::getInstance()->iselect($fields, $conditions, $params,'all',"t.create_time ASC",$joinArray,'t');
 				if (! empty ( $trans_select )) {
 					// 已确认的入库单才有transtions,减库存
 					foreach ( $trans_select as $trans ) {
 						//记录更新product 前的quantity
 						$PRODUCT = ProductDAO::getInstance()->iselect("quantity", "product_id = :pid", [':pid'=>$trans['goods_id']],'one');
 						//product 更新数量
 						$pro_minus = ProductDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => -$trans ['quantity'],
 						], "product_id =:id", [
 								':id' => $trans ['goods_id']
 						] );
 	
 						if (! $pro_minus) {
 							$tT->rollBack();
 							return $this->handleApiFormat ( EnumOther::ACK_FAILURE, '', 'update product quantity failure' );
 						}
 							
 						//product_update_log 商品更新记录
 						$_order_type = Utility::getArrayValue(EnumOriginType::$origin_type, $trans['origin_type']);
 							
 						$log_columns = [
 								'product_id' => $trans ['goods_id'],
 								'update_num' => $trans ['quantity'],
 								'num_unit' => $trans['quantity_unit'],
 								'origin_id' => $id,
 								'origin_no' => $trans['salereturn_no'],
 								'origin_line_id'=> $trans['salereturn_det_id'],
 								'origin_type'=> $trans['origin_type'],
 								'update_time'=> strtotime(date('Y-m-d')),
 								'flag'=> EnumOther::OUT_FLAG,
 								'initial_num'=> $PRODUCT['quantity'],//上期数量
 								'remark'=> $_order_type . EnumOther::MINUS.',销售退货单删除',
 								'warehouse_id' => $trans['warehouse_id'],
 								'create_man' => Yii::$app->user->id,
 						];
 						$res_log = ProductUpdateLogDAO::getInstance()->iinsert($log_columns, true);
 						if(! $res_log){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'product update log failure');
 						}
 							
 						//删除transaction 数据
 						$columns = [
 								'delete_flag'=>EnumOther::DELETED,
 						];
 						$conditions = "transaction_id = :tid";
 						$params = [
 								':tid'=>$trans['transaction_id'],
 						];
 						$trans_update = TransactionDAO::getInstance()->iupdate($columns, $conditions, $params);
 							
 						if(empty($trans_update)){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','tansaction del fail');
 						}
 						// 更新stock_file 分仓表信息
 						$stock_minus = StockPileDAO::getInstance ()->updateAllCounters ( [
 								'quantity' => - $trans ['quantity']
 						], "warehouse_id =:wid and product_id=:pid and delete_flag =:flag", [
 								':wid' => $trans ['warehouse_id'],
 								':pid' => $trans ['goods_id'],
 								':flag' => EnumOther::NO_DELETE
 						] );
 						if(! $stock_minus){
 							$tT->rollBack ();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update stock pile quantity failure');
 						}
 						//更新sell
 						$result = SaleOutDAO::getInstance()->updateSaleOut($trans['saleout_id'],$trans['saleout_det_id'],$trans['quantity']);
 						if(!$result){
 							$tT->rollBack();
 							return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'update saleout failure');
 						}
 					}
 				}
 			}
 				
 			$tT->commit();
 			return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
 		} catch ( \Exception $e ) {
 			$tT->rollBack ();
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
 		}
 	}
 	
 	/**
 	 * @desc 销售出库单导入销售订单
 	 * @author liaojianwen
 	 * @date 2017-05-03
 	 */
 	public function implodeSellInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$pro_head = SellDAO::getInstance()->getSellHead($id);
 		if(empty($pro_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$pro_det = SellDetailDAO::getInstance()->getSellDet($id);
 		if(empty($pro_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		foreach ($pro_det as &$det)
 		{
 			$det['left_quantity'] = $det['minus_quantity'];
 			foreach ( $det['product_unit'] as $unit){
 				if($det['quantity_unit'] == $unit['unit_id']){
 					$det['quantity_rate'] = $unit['rate'];
 					$det['quantity_name'] = $unit['unit_name'];
 				}
 				if($det['second_unit'] == $unit['unit_id']){
 					$det['second_rate'] = $unit['rate'];
 					$det['second_name'] = $unit['unit_name'];
 				}
 			}
 				
 			if($det['second_unit'] ){
 				$det['second_quantity'] = $det['minus_quantity'] / $det['second_rate'];
 			}
 				
 			$det['quantity'] = $det['minus_quantity'] / $det['quantity_rate'];
 			$det['amount'] = round($det['quantity'] * $det['price'] - $det['discount'],2);
 				
 			if($det['second_unit'] ){
 				$tmp_name = floor($det ['quantity'] * $det ['quantity_rate'] / $det ['second_rate']);
 				$tmp_content = fmod($det ['quantity']*$det['quantity_rate'],$det['second_rate']);
 				$det['second_relation'] = $tmp_name. $det['second_name'] .$tmp_content . $det['quantity_name'];
 			}
 				
 		}
//  		dd($pro_det);
 		$result['head'] = $pro_head;
 		$result['det'] = $pro_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 销售退货导入销售订单
 	 * @author liaojianwen
 	 * @date 2017-05-03
 	 */
 	public function implodeSaleOutInfo($id)
 	{
 		if(empty($id)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
 		}
 		$in_head = SaleOutDAO::getInstance()->getSaleOutHead($id);
 		if(empty($in_head)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','head data found');
 		}
 		$in_det = SaleOutDetailDAO::getInstance()->getSaleOutDet($id);
 		if(empty($in_det)){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','detail data found');
 		}
 		foreach ($in_det as &$det)
 		{
 			$det['left_quantity'] = $det['minus_quantity'];
 			foreach ( $det['product_unit'] as $unit){
 				if($det['quantity_unit'] == $unit['unit_id']){
 					$det['quantity_rate'] = $unit['rate'];
 					$det['quantity_name'] = $unit['unit_name'];
 				}
 				if($det['second_unit'] == $unit['unit_id']){
 					$det['second_rate'] = $unit['rate'];
 					$det['second_name'] = $unit['unit_name'];
 				}
 			}
 				
 			if($det['second_unit'] ){
 				$det['second_quantity'] = $det['minus_quantity'] / $det['second_rate'];
 			}
 				
 			$det['quantity'] = $det['minus_quantity'] / $det['quantity_rate'];
 			$det['amount'] = round($det['quantity'] * $det['price'] - $det['discount'],2);
 				
 			if($det['second_unit'] ){
 				$tmp_name = floor($det ['quantity'] * $det ['quantity_rate'] / $det ['second_rate']);
 				$tmp_content = fmod($det ['quantity']*$det['quantity_rate'],$det['second_rate']);
 				$det['second_relation'] = $tmp_name. $det['second_name'] .$tmp_content . $det['quantity_name'];
 			}
 				
 		}
 		
 		$result['head'] = $in_head;
 		$result['det'] = $in_det;
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
 	}
 	
 	/**
 	 * @desc 店铺生成要货单
 	 * @author liaojianwen
 	 * @date 2017-07-28
 	 */
 	public function storeInsertSell($productInfo)
 	{
 		if(!$productInfo){
 			return false;
 		}
 		$tr = Yii::$app->db->beginTransaction();
 		try{
	 		$sellNo = EnumOriginType::SALE.date('YmdHis');
	 		$warehouse_id = EnumOther::DEFAULT_WARE;
	 		$client = ClientDAO::getInstance()->iselect("client_id", "store_id=:sid and delete_flag=:flag", [':sid'=>$productInfo['head']['store_id'],':flag'=> EnumOther::NO_DELETE],'one');
			if(empty($client)){
				$tr->rollBack();
				return false;
			}
	 		$sell_head = [
	 			'sell_no'=>$sellNo,
	 			'sell_date'=> time(),
	 			'warehouse_id' => $warehouse_id,
	 			'customer_id'=> $client['client_id'],
	//  			'handle_man'=> ,//
	 			'create_man'=> '1',//admin
	 			'remark' => $productInfo['head']['remark'],
	 			'sell_amount' => $productInfo['head']['procurement_amount'],
	 		];
	 		$res_head = SellDAO::getInstance()->iinsert($sell_head,true);
	 		if(!$res_head){
	 			$tr->rollBack();
	 			return false;
	 		} else {
		 		foreach ($productInfo['detail'] as $det){
		 			$fields = [
		 				'product_id',
		 				'supply_price',
		 			];
		 			$conditions = "product_id =:pid";
		 			$params=[
		 				':pid'=>$det['scm_product_id'],
		 			];
		 			$product = ProductDAO::getInstance()->iselect($fields, $conditions, $params,'one');
		 			$sell_det =[
		 				'sell_id'=> $res_head,
		 				'product_id'=> $product['product_id'],
		 				'quantity'=> $det['quantity'],
		 				'quantity_unit' => $det['scm_quantity_unit'],
		 				'price'=> $product['supply_price'],//供货价
		 				'amount' => $det['quantity'] * $product['supply_price'],
		 				'base_quantity'=> $det['base_quantity'],
		 				'base_unit' => $det['scm_base_unit'],
		 				'minus_quantity' => $det['base_quantity'],
		 			];
		 			
		 			$res_det = SellDetailDAO::getInstance()->iinsert($sell_det, true);
		 			if(!$res_det){
		 				$tr->rollBack();
		 				return  false;
		 			}
		 			
		 		}
		 	}
		 $tr->commit();
		 return true;
	 	
	 	}catch (\Exception $e){
	 		$tr->rollBack();
	 		return false;
	 	}
 	}
 	
 	/**
 	 * @desc 确认销售订单
 	 * @author liaojianwen
 	 * @date 2017-07-28
 	 */
 	public function confirmSell($id)
 	{
 		if(!$id){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', '');
 		}
 		$man = SellDAO::getInstance()->findByPk($id,"handle_man");
 		if(!$man['handle_man']){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no handle_man');
 		}
 		$columns =[
 			'confirm_flag' => EnumOther::CONFIRM,
 		];
 		$conditions ="sell_id =:sid";
 		$params =[
 			':sid'=>$id
 		];
 		$res_sell = SellDAO::getInstance()->iupdate($columns, $conditions, $params);
 		if(!$res_sell){
 			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', '');
 		}
 		return $this->handleApiFormat(EnumOther::ACK_SUCCESS, '');
 	}
 	
 	/**
 	 * @desc 
 	 * @author liaojianwen
 	 */
 	public function storeInsertSaleReturn($saleInfo)
 	{
 		if(!$saleInfo){
 			return false;
 		}
 		$tr = Yii::$app->db->beginTransaction();
 		try{
 			$sellNo = EnumOriginType::SALE_RETURN.date('YmdHis');
 			$warehouse_id = EnumOther::DEFAULT_WARE;
 			$client = ClientDAO::getInstance()->iselect("client_id", "store_id=:sid and delete_flag=:flag", [':sid'=>$saleInfo['head']['store_id'],':flag'=> EnumOther::NO_DELETE],'one');
 			if(empty($client)){
 				$tr->rollBack();
 				return false;
 			}
 			$sell_head = [
 					'salereturn_no'=>$sellNo,
 					'salereturn_date'=> time(),
 					'warehouse_id' => $warehouse_id,
 					'customer_id'=> $client['client_id'],
 					'salereturn_type' => EnumOriginType::origin_store_return,
 					//  			'handle_man'=> ,//
 					'create_man'=> '1',//admin
 					'remark' => $saleInfo['head']['remark'],
 					'salereturn_amount' => $saleInfo['head']['purchase_return_amount'],
 					// 'salereturn_amount' => $saleInfo['head']['outstore_amount'],
 			];
 			$res_head = SaleReturnDAO::getInstance()->iinsert($sell_head,true);
 			if(!$res_head){
 				$tr->rollBack();
 				return false;
 			} else {
 				foreach ($saleInfo['detail'] as $det){
 					$fields = [
 							'product_id',
//  							'supply_price',
 					];
 					$conditions = "product_id =:pid";
 					$params=[
 							':pid'=>$det['scm_product_id'],
 					];
 					$product = ProductDAO::getInstance()->iselect($fields, $conditions, $params,'one');
 		
 					$sell_det =[
 							'salereturn_id'=> $res_head,
 							'product_id'=> $product['product_id'],
 							'quantity'=> $det['quantity'],
 							'quantity_unit' => $det['scm_quantity_unit'],
 							'price'=> $det['price'],
 							'amount' => $det['quantity'] * $det['price'],
 							'base_quantity'=> $det['base_quantity'],
 							'base_unit' => $det['scm_base_unit'],
//  							'minus_quantity' => $det['base_quantity'],
 					];
 					
 					$res_det = SaleReturnDetailDAO::getInstance()->iinsert($sell_det, true);
 					if(!$res_det){
 						$tr->rollBack();
 						return  false;
 					}
 		
 				}
 			}
 			$tr->commit();
 			return true;
 			
 			 
 		}catch (\Exception $e){
 			$tr->rollBack();
 			return false;
 		}
 	}
 }